import { defineStore } from "pinia";
import {
  type userType,
  store,
  router,
  resetRouter,
  routerArrays,
  storageLocal
} from "../utils";
import {
  type RefreshTokenResult,
  getLogin,
  getUserInfo,
  refreshTokenApi
} from "@/api/user";
import { useMultiTagsStoreHook } from "./multiTags";
import { type DataInfo, setToken, removeToken, userKey } from "@/utils/auth";

export const useUserStore = defineStore("pure-user", {
  state: (): userType => ({
    // id
    // id: storageLocal().getItem<DataInfo<number>>(userKey)?.id ?? undefined,
    // 头像
    avatar: storageLocal().getItem<DataInfo<number>>(userKey)?.avatar ?? "",
    // 用户名
    username: storageLocal().getItem<DataInfo<number>>(userKey)?.username ?? "",
    // 昵称
    nickname: storageLocal().getItem<DataInfo<number>>(userKey)?.nickname ?? "",
    // 页面级别权限
    roles: storageLocal().getItem<DataInfo<number>>(userKey)?.roles ?? [],
    // 按钮级别权限
    permissions:
      storageLocal().getItem<DataInfo<number>>(userKey)?.permissions ?? [],
    // 是否勾选了登录页的免登录
    isRemembered: false,
    // 登录页的免登录存储几天，默认7天
    loginDay: 7,
    // 租户ID
    tenantId:
      storageLocal().getItem<DataInfo<number>>(userKey)?.tenantId ?? undefined
  }),
  actions: {
    /** 存储ID */
    SET_ID(id: number) {
      this.id = id;
    },
    /** 存储头像 */
    SET_AVATAR(avatar: string) {
      this.avatar = avatar;
    },
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username;
    },
    /** 存储昵称 */
    SET_NICKNAME(nickname: string) {
      this.nickname = nickname;
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles;
    },
    /** 存储租户ID */
    SET_TENANTID(tenantId: number) {
      this.tenantId = tenantId;
    },
    /** 存储按钮级别权限 */
    SET_PERMS(permissions: Array<string>) {
      this.permissions = permissions;
    },
    /** 存储是否勾选了登录页的免登录 */
    SET_ISREMEMBERED(bool: boolean) {
      this.isRemembered = bool;
    },
    /** 设置登录页的免登录存储几天 */
    SET_LOGINDAY(value: number) {
      this.loginDay = Number(value);
    },
    /** 登入 */
    async loginByUsername(data) {
      return new Promise<any>((resolve, reject) => {
        getLogin(data)
          .then(async loginRes => {
            if (loginRes?.code === 0) {
              // 登录成功，获取用户信息
              try {
                const userInfoRes = await getUserInfo();
                if (userInfoRes?.code === 0) {
                  // 构造token数据结构
                  const ui = userInfoRes.data as any;
                  const tokenData = {
                    accessToken: loginRes.data,
                    refreshToken: loginRes.data, // 如果没有单独的refreshToken，使用accessToken
                    expires: new Date(Date.now() + 2 * 60 * 60 * 1000), // 2小时后过期
                    // ID
                    id: ui?.id ?? undefined,
                    // 头像
                    avatar: ui?.avatar ?? ui?.imageUrl ?? "",
                    // 用户名/昵称兜底为 name
                    username: ui?.username ?? ui?.name ?? "",
                    nickname: ui?.nickname ?? ui?.name ?? "",
                    // 租户ID
                    tenantId: ui?.tenantId ?? undefined,
                    // 角色字段兼容 role / roles
                    roles: Array.isArray(ui?.roles)
                      ? ui.roles
                      : ui?.role
                        ? [ui.role]
                        : [],
                    // 权限（后端未返回则给空数组）
                    permissions: Array.isArray(ui?.permissions)
                      ? ui.permissions
                      : []
                  };
                  setToken(tokenData);
                  // 设置租户ID到store
                  if (ui?.tenantId) {
                    this.SET_TENANTID(ui.tenantId);
                  }
                  resolve({ success: true, data: tokenData });
                } else {
                  reject(new Error(userInfoRes?.message || "获取用户信息失败"));
                }
              } catch (error) {
                reject(error);
              }
            } else {
              reject(new Error(loginRes?.message || "登录失败"));
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 前端登出（不调用接口） */
    logOut() {
      this.username = "";
      this.roles = [];
      this.permissions = [];
      removeToken();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();
      router.push("/login");
    },
    /** 刷新`token` */
    async handRefreshToken(data) {
      return new Promise<RefreshTokenResult>((resolve, reject) => {
        refreshTokenApi(data)
          .then(data => {
            if (data) {
              setToken(data.data);
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
